package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissionService;
import com.qf.vo.PermUpdateVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lixu
 */
@Service
public class DtsPermissionServiceImpl implements DtsPermissionService {

    @Autowired
    private DtsPermissionMapper dtsPermissionMapper;
    @Override
    public Set<String> findPermissionListByRoleId(Integer roleId) {
        Set<String> permissionListByRoleId = dtsPermissionMapper.findPermissionListByRoleId(roleId);
        //1、如果是超级管理员
        if(permissionListByRoleId.contains("*")){
            //1.1将所有权限加载出来并返回
            return dtsPermissionMapper.findPermissionList();
        }
        //2、不是超级管理员 加载自己的权限
        return permissionListByRoleId;
    }

    //更新权限
    @Override
    @Transactional
    public void update(PermUpdateVo permUpdateVo) {

        //1:根据角色ID 删除 原有权限
        dtsPermissionMapper.delete(new LambdaQueryWrapper<DtsPermission>()
          .eq(DtsPermission::getRoleId,permUpdateVo.getRoleId()));

        //2:添加 新的权限
        //批量添加  insert int () values (),(),(),()
        dtsPermissionMapper.insertBatch(permUpdateVo);

    }

    //查询当前用户拥有的所有权限
    @Override
    public Set<String> findPermissionListByRoleIds(Integer[] roleIds) {
        List<DtsPermission> dtsPermissionList = dtsPermissionMapper.selectList(new QueryWrapper<DtsPermission>()
                .in("role_id", roleIds));
        return dtsPermissionList.stream()
                .map(DtsPermission::getPermission).collect(Collectors.toSet());
    }
}
